﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TRPOP.CMS.Publish;
using System.Data;
using Newtonsoft.Json;

namespace TRPOP.CMS.Web.Admin
{
    /// <summary>
    /// admin_task_watch 的摘要说明
    /// </summary>
    public class admin_task_watch : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            CheckIfRunningTask();
            switch (TRPOP.Common.RequestHelper.RequestString("ac").ToLower())
            {
                case "checktask"://监视已执行的任务
                    WatchTask(context);
                    break;
                case "cancelmytask"://取消个人所有的任务
                    CancelTask(context);
                    break;
            }
            return;
        }
        //检查是否正在执行发布任务，如果没有执行，则根据情况激活相关的线程
        private void CheckIfRunningTask()
        {
            if (!MultiThreadPub.IsRunning)
            {
                new MultiThreadPub().ActivateThread();
            }
        }
        private void WatchTask(HttpContext context)
        {
            int intUserID = (TRPOP.CMS.Plugin.IAdminUserAccess.GetInstance().getUserBaseInfo() as TRPOP.CMS.UserManage.AdminUserInfo).UserBaseId;
            if (intUserID <= 0)
            {
                context.Response.End();
                return;
            }
            DataTable oTable = PubTaskDAL.GetExecedInfo(intUserID);
            JavaScriptObject oInfo = new JavaScriptObject();
            JavaScriptObject oitemlist = new JavaScriptObject();
            if (oTable != null && oTable.Rows.Count > 0)
            {
                foreach (DataRow Row in oTable.Rows)
                {
                    oitemlist.Add(Row[0].ToString(), Row[1].ToString() == "2" ? "success" : "false");
                    //if (Row[1].ToString() == "2")
                    PubTaskDAL.ShowedInfoById(int.Parse(Row[0].ToString()));
                }
            }
            oInfo.Add("items", oitemlist);
            context.Response.Write(JavaScriptConvert.SerializeObject(oInfo));
        }
        private void CancelTask(HttpContext context)
        {
            int intUserID = (TRPOP.CMS.Plugin.IAdminUserAccess.GetInstance().getUserBaseInfo() as TRPOP.CMS.UserManage.AdminUserInfo).UserBaseId;
            if (intUserID <= 0)
            {
                context.Response.End();
                return;
            }
            context.Response.Write(PubTaskDAL.CancelAllInfoUserId(intUserID).ToString().ToLower());
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}